const { Permission } = require('../models/Middle')
const { Op } = require('sequelize')
const sequelize = require('../utils/seq')
const moment = require('moment')
const seq = require('../utils/seq')
// 新增
async function add (permission) {
  permission.ctime = moment().format('YYYY-MM-DD HH:mm:ss')
  permission.mtime = moment().format('YYYY-MM-DD HH:mm:ss')
  try {
    return await Permission.create(permission)
  } catch (error) {
    throw error
  }
}

// 查询（分页、排序、模糊查询搜索）
async function findAll (query) {
  try {
    const size = query.size ? parseInt(query.size) : 10
    const page = query.page ? parseInt(query.page) : 1
    const { count, rows } = await Permission.findAndCountAll({
      offset: (page - 1) * size, // 分页
      limit: size,
      distinct: true,
      order: [
        [query.order ? query.order : 'ctime', query.sort ? query.sort : 'desc']
      ], // 排序
      where: { //测试模糊查询
        type: {
          [Op.like]: query.type ? `%${query.type}%` : '%%'
        },
        [Op.or]: [
          { name: { [Op.like]: query.search ? `%${query.search}%` : '%%' } },
          { path: { [Op.like]: query.search ? `%${query.search}%` : '%%' } },
          { perms: { [Op.like]: query.search ? `%${query.search}%` : '%%' } },
          { tag: { [Op.like]: query.search ? `%${query.search}%` : '%%' } },
          { ctime: { [Op.like]: query.search ? `%${query.search}%` : '%%' } },
          { mtime: { [Op.like]: query.search ? `%${query.search}%` : '%%' } },
          { remark: { [Op.like]: query.search ? `%${query.search}%` : '%%' } },
        ]
      }
    })
    return {
      count,
      data: rows
    }
  } catch (error) {
    throw error
  }
}

// 修改
async function update (permission) {
  permission.mtime = moment().format('YYYY-MM-DD HH:mm:ss')
  try {
    return await Permission.update(permission, {
      where: {
        id: permission.id
      }
    })
  } catch (error) {
    throw error
  }
}

// 删除（先删除权限相关联的表）
async function deleteById (id) {
  try {
    await seq.query(`delete from role_perm where permissionId='${id}'`)
    return await Permission.destroy({
      where: {
        id
      }
    })
  } catch (error) {
    throw error
  }
}

// 根据id查询
async function findOneById (id) {
  try {
    return await Permission.findOne({
      where: {
        id
      }
    })
  } catch (error) {
    throw error
  }
}

// 查询不重复的tag列表
async function findTags () {
  try {
    return await Permission.findAll({
      attributes: [[sequelize.fn('DISTINCT', sequelize.col('tag')), 'ta']],
    })
  } catch (error) {
    throw error
  }
}

// 查询模块下的接口列表
async function findTagPerms (tag) {
  try {
    return await Permission.findAll({
      where: tag
    })
  } catch (error) {
    throw error
  }
}

module.exports = {
  add,
  findAll,
  update,
  deleteById,
  findOneById,
  findTags,
  findTagPerms
}